import os
import sys
import configparser

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DIRNAME = os.path.basename(BASE_DIR)
DATAS_DIR = os.path.join(BASE_DIR, '..', 'datas')
LOG_DIR = os.path.join(DATAS_DIR, 'logs')

global_conf = configparser.ConfigParser()
global_conf.read(os.path.join(os.environ.get('PROJECT_SETTINGS_DIR', ''), 'settings.ini'))


def get_section_value(key, default=None, datatype='raw'):
    keymap = {'raw': global_conf.get, 'int': global_conf.getint, 'boolean': global_conf.getboolean, 'float': global_conf.getfloat}
    try:
        value = keymap[datatype]('core', key)
    except configparser.NoOptionError:
        value = default
    return value


# Create logs dir if the directory not exist
if not os.path.exists(DATAS_DIR):
    os.mkdir(DATAS_DIR)
if not os.path.exists(LOG_DIR):
    os.mkdir(LOG_DIR)

chdir = os.path.join(BASE_DIR)

wsgi_app = 'bbs.wsgi'

daemon = get_section_value('DAEMON', True, 'boolean')
workers = get_section_value('WORKERS', 5, 'int')

bind = get_section_value('BIND_IP', '127.0.0.1') + ":" + get_section_value('BASE_PORT', '809') + '1'

# Pid
pidfile = os.path.join(DATAS_DIR, str(DIRNAME) + '.pid')

limit_request_line = get_section_value('LIMIT_REQUEST_LINE', 8190, 'int')

errorlog = os.path.join(LOG_DIR, DIRNAME + '_gunicorn_error.log')
accesslog = os.path.join(LOG_DIR, DIRNAME + '_gunicorn_access.log')
